#pragma Once
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

extern Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    CONN_ERR
};

void Usage(std::string proc)
{
    std::cout << "Usage: " << "[" << proc << " serverip  sserverport] " << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        int socketfd = socket(AF_INET, SOCK_STREAM, 0);
        if (socketfd < 0)
        {
            lg(Fatal, "create socket fail,socket : %d ", socketfd);
            exit(SOCKET_ERR);
        }

        // tcp客户端要不要bind？1 要不要显示的bind？0 系统进行bind，随机端口
        // 客户端发起connect的时候，进行自动随机bind
        int n = connect(socketfd, (const struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            std::cout << "connect fail " << std::endl;
            exit(CONN_ERR);
        }
        else
        {
            std::cout << "连接成功" << std::endl;
        }

        std::cout << "Please Enter@ ";
        std::string message;
        std::getline(std::cin, message);

        n = write(socketfd, message.c_str(), message.size());
        if (n < 0)
        {
            std::cout << "write fail" << std::endl;
            break;
        }

        char inbuff[1024];
        n = read(socketfd, inbuff, sizeof(inbuff));
        if (n < 0)
        {
            std::cout << "read fail" << std::endl;
            break;
        }

        inbuff[n] = 0;
        std::cout << inbuff << std::endl;

        close(socketfd);
    }

    return 0;
}